package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类 -- 订单超时取消定时任务
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单 -- 每分钟检测一次
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeoutOrders(){
        LocalDateTime now = LocalDateTime.now();
        log.info("定时处理超时订单:{}", now);
        // 设置超时时间在overTime之前下单的都为超时检测订单
        LocalDateTime overTime = now.minusMinutes(15);
        Integer status = Orders.PENDING_PAYMENT;
        // 获取超时未支付的订单列表
        List<Orders> ordersList = orderMapper.selectTimeOut(status, overTime);
        // 调用订单服务接口，修改订单状态为已取消
        if (ordersList != null && !ordersList.isEmpty()){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时，自动取消");
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 处理配送中却未完成的订单 -- 每天凌晨一点检测
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processNotCompletedOrders(){
        LocalDateTime now = LocalDateTime.now();
        log.info("定时处理配送中订单:{}", now);
        // 设置今天之前的订单
        LocalDateTime overTime = now.minusHours(1);
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        // 获取配送中的订单
        List<Orders> ordersList = orderMapper.selectTimeOut(status, overTime);
        if (ordersList != null && !ordersList.isEmpty()){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }
}
